package com.hefu.virtuallife.ui.map;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.hefu.virtuallife.R;
import com.hefu.virtuallife.ui.VoiceActivity;
import com.hefu.virtuallife.utils.GoWhere;
import com.hefu.virtuallife.utils.UiUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zc on 2018/7/4.
 */

public class TakeTaxiActivity extends VoiceActivity implements AMapLocationListener, AMap.OnCameraChangeListener, AMap.OnMapClickListener, LocationSource {
    @BindView(R.id.tab_layout)
    TabLayout tab_layout;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.img_return)
    ImageView img_return;
    public String[] taxi_type;

    private AMap aMap;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption = null;
    private OnLocationChangedListener listener;
    private Marker mainMarker;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_take_taxi;
    }

    @Override
    protected void initVariables(@Nullable Bundle savedInstanceState) {
        tab_layout.setTabMode(TabLayout.MODE_FIXED);
        taxi_type = UiUtils.getStringArray(R.array.taxi_type);
        for (String name : taxi_type) {
            tab_layout.addTab(tab_layout.newTab().setText(name));
        }
        mapView.onCreate(savedInstanceState);

        img_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        init();
    }

    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(20));
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);


        MyLocationStyle locationStyle = new MyLocationStyle();
        locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_direct));
        locationStyle.strokeColor(Color.TRANSPARENT);
        locationStyle.radiusFillColor(Color.TRANSPARENT);
        locationStyle.strokeWidth(0);
        aMap.setMyLocationStyle(locationStyle);

        // 设置定位监听
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式，参见类AMap。
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        // 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
        aMap.setMyLocationEnabled(true);


        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMapClickListener(this);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (listener != null && mlocationClient != null) {
            listener.onLocationChanged(amapLocation);//
            if (amapLocation.getErrorCode() == 0) {
                amapLocation.getLocationType();
                double lat = amapLocation.getLatitude();
                double lon = amapLocation.getLongitude();
                LatLng ll = new LatLng(lat, lon);
                amapLocation.getAccuracy();
                String city = amapLocation.getCity();
                tvCity.setText(city);
                addMainMarker(ll);
                addRandomCar(lat, lon);

                aMap.moveCamera(CameraUpdateFactory.zoomTo(20));
                aMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(new CameraPosition(ll, 20, 0, 0)));

            } else {
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public void onCameraChange(CameraPosition position) {
        if (mainMarker != null) {
            mainMarker.setPosition(position.target);
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {
        LatLng ll = position.target;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
        Dialog dialog = new Dialog(TakeTaxiActivity.this, R.style.transDialog);
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.layout_dialog_texi);
        dialog.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    public void addRandomCar(double lat, double lon) {
        for (int i = 1; i < 10; i++) {
            double a = lat + 0.0002 * i;
            double b = lon + 0.0002 * i;
            LatLng la = new LatLng(a, b);
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(la);
            markerOption.draggable(true);
            markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_car));
            Marker marker = aMap.addMarker(markerOption);
            marker.setRotateAngle(new Random().nextInt(360));
        }

    }

    @OnClick(R.id.tv_city)
    protected void onCityTextClick() {
        List<HotCity> hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));

        CityPicker.getInstance()
                .setFragmentManager(getSupportFragmentManager())
                .enableAnimation(true)
                .setLocatedCity(new LocatedCity("上海", "上海", "101020100"))
                .setHotCities(hotCities)
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data == null) {
                            return;
                        }
                        tvCity.setText(data.getName());
                        Toast.makeText(getApplicationContext(), data.getName(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onLocate() {
                        CityPicker.getInstance()
                                .locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                    }
                })
                .show();
    }

    @OnClick(R.id.tv_release)
    protected void onMsgTextClick() {
        GoWhere.toTaxiMsg(this);
    }


    @Override
    protected void uiProcess() {
        Dialog dialog = new Dialog(TakeTaxiActivity.this, R.style.transDialog);
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.layout_dialog_texi_result);
        dialog.show();
    }

    @OnClick(R.id.imgHistory)
    protected void onHistoryClick() {
        GoWhere.toTaxiHistory(this);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        addMainMarker(latLng);
    }

    private void addMainMarker(LatLng latLng) {
        if (mainMarker != null) {
            mainMarker.remove();
        }
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.draggable(true);
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(UiUtils.view2Bitmap(this, R.layout.layout_map_main_marker)));
        mainMarker = aMap.addMarker(markerOptions);
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        listener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {

    }
}
